"""
用户相关业务接口
"""
import json
import os
from conf import settings
from db import db_handler
from lib import common


# 注册接口
def register_interface(username, password, balance=15000):
    user_dic = db_handler.select(username)
    if user_dic:
        return False, '用户已存在，请重新输入！'

    password = common.get_pwd_md5(password)

    user_dic = {
        'username': username,
        'password': password,
        'balance': balance,
        'flow': [],
        'shop_car': {},
        'locked': False
    }

    db_handler.save(user_dic)
    return True, f'{username}注册成功！'


# 登录接口
def login_interface(username, password):
    user_dic = db_handler.select(username)
    if user_dic and not user_dic['locked']:
        password = common.get_pwd_md5(password)
        if password == user_dic.get('password'):
            return True, f'用户[{username}] 登录成功'
        else:
            return False, '密码输入错误,请重新输入！'
    if user_dic['locked']:
        return False, '用户已经被锁定！'

    return False, '用户不存在,请重新输入！'

